'use client'

import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import Link from "next/link"
import { useEffect, useRef, useState, useCallback } from "react"

// PDF文件信息接口
interface PDFFileInfo {
  name: string;
  path: string;
  size: number;
  lastModified: string;
}

// PDF.js 类型定义
type PDFDocumentProxy = import('pdfjs-dist').PDFDocumentProxy
type PDFPageProxy = import('pdfjs-dist').PDFPageProxy

// 使用PDF.js渲染PDF文件的组件
function PDFViewer({ pdfPath }: { pdfPath: string }) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [pageNum, setPageNum] = useState(1)
  const [numPages, setNumPages] = useState(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [scale, setScale] = useState(1.5)
  const [pdfDocument, setPdfDocument] = useState<PDFDocumentProxy | null>(null)

  // 渲染指定页面 - 使用useCallback优化
  const renderPage = useCallback(async (pageNum: number) => {
    if (!pdfDocument || !canvasRef.current) return

    try {
      const page = await pdfDocument.getPage(pageNum)
      const canvas = canvasRef.current
      const context = canvas.getContext('2d')
      
      if (!context) {
        // 不再设置错误状态，而是静默处理
        console.error('无法获取Canvas上下文')
        return
      }

      const viewport = page.getViewport({ scale })
      canvas.height = viewport.height
      canvas.width = viewport.width

      const renderContext = {
        canvasContext: context,
        viewport
      }

      await page.render(renderContext).promise
    } catch (err) {
      // 不再设置错误状态，而是静默处理
      console.error('渲染PDF页面失败:', err)
    }
  }, [pdfDocument, scale])

  // 加载PDF文档
  useEffect(() => {
    let isMounted = true
    
    const loadPdf = async () => {
      try {
        if (!isMounted) return
        setLoading(true)
        setError(null) // 重置错误状态
        
        // 动态导入PDF.js
        const pdfjs = await import('pdfjs-dist')
        // 设置worker路径 - 使用类型断言解决红色波浪线问题
        const pdfjsWorker = await import('pdfjs-dist/build/pdf.worker.mjs') as any
        // 确保正确设置worker路径
        pdfjs.GlobalWorkerOptions.workerSrc = pdfjsWorker.default || pdfjsWorker
        
        // 加载PDF文件
        const loadingTask = pdfjs.getDocument(pdfPath)
        const pdf = await loadingTask.promise
        
        if (!isMounted) return
        
        setNumPages(pdf.numPages)
        setPdfDocument(pdf)
        setLoading(false)
      } catch (err) {
        console.error('加载PDF文件失败:', err)
        if (isMounted) {
          // 不再显示错误提示，而是自动在新窗口中打开PDF
          window.open(pdfPath, '_blank', 'noopener,noreferrer')
          setLoading(false)
        }
      }
    }

    loadPdf()
    
    // 清理函数，防止内存泄漏
    return () => {
      isMounted = false
      // 清理PDF文档资源
      if (pdfDocument) {
        pdfDocument.destroy().catch(console.error)
      }
    }
  }, [pdfPath])

  // 当页码变化或PDF文档加载完成时渲染页面
  useEffect(() => {
    if (pdfDocument && !loading) {
      renderPage(pageNum)
    }
  }, [pdfDocument, pageNum, renderPage, loading])

  // 处理窗口大小变化
  useEffect(() => {
    const handleResize = () => {
      if (pdfDocument && !loading) {
        renderPage(pageNum)
      }
    }

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [pdfDocument, pageNum, renderPage, loading])

  // 切换到上一页
  const prevPage = () => {
    if (pageNum > 1) {
      setPageNum(pageNum - 1)
    }
  }

  // 切换到下一页
  const nextPage = () => {
    if (pageNum < numPages) {
      setPageNum(pageNum + 1)
    }
  }

  // 缩放控制
  const zoomIn = () => {
    setScale(prevScale => Math.min(prevScale + 0.25, 3))
  }

  const zoomOut = () => {
    setScale(prevScale => Math.max(prevScale - 0.25, 0.5))
  }

  const resetZoom = () => {
    setScale(1.5)
  }

  if (loading) {
    return (
      <div className="flex justify-center items-center h-full">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto mb-4"></div>
          <p>正在加载PDF文件，请稍候...</p>
        </div>
      </div>
    )
  }

  // 完全移除错误状态的显示，直接显示一个友好的提示和打开按钮
  if (!pdfDocument || error) {
    return (
      <div className="flex flex-col items-center justify-center h-full bg-gray-100 p-4 rounded-md">
        <p className="text-gray-600 mb-4">PDF文件将在新窗口中打开查看</p>
        <button 
          onClick={() => window.open(pdfPath, '_blank', 'noopener,noreferrer')}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          在新窗口中打开PDF
        </button>
      </div>
    )
  }

  return (
    <div className="flex flex-col h-full">
      <div className="flex justify-center mb-2">
        <div className="flex space-x-2">
          <button
            onClick={zoomOut}
            className="px-3 py-1 bg-gray-200 rounded hover:bg-gray-300"
            title="缩小"
          >
            -
          </button>
          <button
            onClick={resetZoom}
            className="px-3 py-1 bg-gray-200 rounded hover:bg-gray-300"
            title="重置缩放"
          >
            {Math.round(scale * 100)}%
          </button>
          <button
            onClick={zoomIn}
            className="px-3 py-1 bg-gray-200 rounded hover:bg-gray-300"
            title="放大"
          >
            +
          </button>
        </div>
      </div>
      
      <div className="flex-grow overflow-auto">
        <div className="flex justify-center">
          <canvas ref={canvasRef} className="shadow-lg"></canvas>
        </div>
      </div>
      
      <div className="flex justify-between items-center mt-4 px-4 py-2 bg-gray-100 rounded-md">
        <button 
          onClick={prevPage} 
          disabled={pageNum <= 1}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed"
        >
          上一页
        </button>
        <p className="text-center">
          第 {pageNum} 页 / 共 {numPages} 页
        </p>
        <button 
          onClick={nextPage} 
          disabled={pageNum >= numPages}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 disabled:bg-gray-300 disabled:cursor-not-allowed"
        >
          下一页
        </button>
      </div>
    </div>
  )
}

export default function TopicPage() {
  // 状态管理
  const [pdfFiles, setPdfFiles] = useState<PDFFileInfo[]>([])
  const [selectedPdf, setSelectedPdf] = useState<string>("") // 初始不选择任何PDF
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  
  // 获取PDF文件列表
  useEffect(() => {
    const fetchPdfFiles = async () => {
      try {
        setLoading(true)
        const response = await fetch('/api/pdfs')
        
        if (!response.ok) {
          throw new Error(`获取PDF列表失败: ${response.status}`)
        }
        
        const data = await response.json()
        setPdfFiles(data.pdfFiles || [])
        
        // 移除自动选择第一个PDF文件的逻辑
        // if (data.pdfFiles && data.pdfFiles.length > 0 && !selectedPdf) {
        //   setSelectedPdf(data.pdfFiles[0].path)
        // }
        
        setLoading(false)
      } catch (err) {
        console.error('获取PDF文件列表失败:', err)
        setError('无法加载PDF文件列表，请稍后再试')
        setLoading(false)
      }
    }
    
    fetchPdfFiles()
  }, [])
  
  // 处理PDF选择
  // 处理PDF选择
  const handleSelectPdf = (pdfPath: string) => {
  // 直接在新窗口中打开PDF，而不是在当前页面加载
  openPdfInNewWindow(pdfPath);
  // 仍然设置selectedPdf，以便UI能够显示当前选中的文件
  setSelectedPdf(pdfPath);
  }
  
  // 格式化文件大小
  const formatFileSize = (bytes: number) => {
    if (bytes < 1024) return `${bytes} B`
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(2)} KB`
    return `${(bytes / (1024 * 1024)).toFixed(2)} MB`
  }
  
  return (
    <div className="container mx-auto px-2 sm:px-3 md:px-4 py-6 sm:py-8 md:py-10">
      <Card className="max-w-4xl mx-auto">
        <CardHeader>
          <CardTitle className="text-2xl">关于投票主题</CardTitle>
          <div className="flex justify-end">
            <Link href="/about" passHref>
              <Button variant="outline" size="sm">返回关于页面</Button>
            </Link>
          </div>
        </CardHeader>
        <CardContent>
          {/* PDF文件列表 */}
          <div className="mb-6 border rounded-md p-4 bg-gray-50">
            <h3 className="text-lg font-medium mb-3">可用的PDF文件</h3>
            <p className="text-sm text-gray-500 mb-3">点击文件名或右侧图标可在新窗口中打开PDF文件</p>
            
            {loading && (
              <div className="flex items-center justify-center py-4">
                <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500 mr-2"></div>
                <p>加载中...</p>
              </div>
            )}
            
            {error && (
              <div className="text-red-500 py-2">{error}</div>
            )}
            
            {!loading && !error && pdfFiles.length === 0 && (
              <div className="text-gray-500 py-2">没有找到PDF文件</div>
            )}
            
            {!loading && !error && pdfFiles.length > 0 && (
              <ul className="divide-y">
                {pdfFiles.map((file) => (
                  <li 
                    key={file.path} 
                    className={`py-2 px-3 cursor-pointer hover:bg-blue-50 flex justify-between items-center ${selectedPdf === file.path ? 'bg-blue-100' : ''}`}
                    onClick={() => handleSelectPdf(file.path)}
                    onDoubleClick={() => openPdfInNewWindow(file.path)}
                  >
                    <div className="flex items-center">
                      <svg className="w-5 h-5 mr-2 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z" />
                      </svg>
                      <span className="font-medium">{file.name}</span>
                    </div>
                    <div className="flex items-center">
                      <span className="text-sm text-gray-500 mr-2">{formatFileSize(file.size)}</span>
                      <button 
                        onClick={(e) => {
                          e.stopPropagation(); // 阻止事件冒泡，避免触发li的onClick
                          openPdfInNewWindow(file.path);
                        }}
                        className="text-blue-500 hover:text-blue-700 text-sm"
                        title="在新窗口中打开"
                      >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                        </svg>
                      </button>
                    </div>
                  </li>
                ))}
              </ul>
            )}
          </div>
          
          {/* PDF查看器 */}
          <div className="w-full" style={{ height: "70vh" }}>
            {selectedPdf ? (
              <PDFViewer pdfPath={selectedPdf} />
            ) : (
              <div className="flex flex-col items-center justify-center h-full bg-gray-100 p-4 rounded-md">
                <p className="text-gray-500">请从上方列表选择一个PDF文件查看</p>
              </div>
            )}
          </div>
          
          <div className="flex justify-center mt-8">
            <Link href="/" passHref>
              <Button>返回首页</Button>
            </Link>
          </div>
        </CardContent>
      </Card>
    </div>
  )
}

// 在新窗口中打开PDF文件
const openPdfInNewWindow = (pdfPath: string) => {
  window.open(pdfPath, '_blank', 'noopener,noreferrer')
}